import { defineStore } from 'pinia'
import request from '@/utils/request'

interface UserState {
  username: string
  role: string
  avatar: string
  isLoggedIn: boolean
}

export const useUserStore = defineStore({
  id: 'user',
  
  state: (): UserState => ({
    username: localStorage.getItem('username') || '',
    role: localStorage.getItem('role') || '',
    avatar: localStorage.getItem('avatar') || '',
    isLoggedIn: localStorage.getItem('isLoggedIn') === 'true'
  }),

  actions: {
    setToken(token: string) {
      localStorage.setItem('token', token)
    },

    login(userData: { username: string; role: string; avatar: string; token: string }) {
      this.username = userData.username
      this.role = userData.role
      this.avatar = userData.avatar || 'https://q1.qlogo.cn/g?b=qq&nk=7097341&s=100'
      this.isLoggedIn = true
      
      // 保存到 localStorage
      localStorage.setItem('username', userData.username)
      localStorage.setItem('role', userData.role)
      localStorage.setItem('avatar', userData.avatar || 'https://q1.qlogo.cn/g?b=qq&nk=7097341&s=100')
      localStorage.setItem('isLoggedIn', 'true')
      this.setToken(userData.token)
    },

    logout() {
      this.username = ''
      this.role = ''
      this.avatar = ''
      this.isLoggedIn = false
      
      // 清除 localStorage
      localStorage.removeItem('username')
      localStorage.removeItem('role')
      localStorage.removeItem('avatar')
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('token')
    },

    async initializeFromStorage() {
      const token = localStorage.getItem('token')
      if (!token) {
        this.logout()
        return false
      }

      try {
        const response = await request.get('/auth/profile')
        const { status, data } = response.data
        
        if (status === 'success' && data) {
          this.login({
            username: data.username,
            role: data.role,
            avatar: data.avatar || 'https://q1.qlogo.cn/g?b=qq&nk=7097341&s=100',
            token: token // 保持现有token
          })
          return true
        } else {
          this.logout()
          return false
        }
      } catch (error) {
        console.error('Failed to initialize user:', error)
        this.logout()
        return false
      }
    }
  }
}) 